//
//  MaterialAcceptCreateController.m
//  ERP
//
//  Created by QA on 16/10/9.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MaterialAcceptResultsController.h"
#import "GETableView.h"

#import "GEInputTableViewCell.h"
#import "FileUploadModel.h"
#import "UploadViewController.h"
#import "PreviewLocalFileHelper.h"
#import "GEObjectButton.h"
#import "FileSizeFormatHelper.h"
#import "FileTypeIcon.h"
#import "NSKeyedArchiverUserLogin.h"
#import "GEPickerTextField.h"
#import "NSDictionary+DataFormat.h"
#import "MaterialAcceptCreateCell.h"
#import "MaterialAcceptResultsAddController.h"

#import "AutoTextTableViewCell.h"
#import "MaterialAcceptNextCell.h"
#import "DownFileInfoCell.h"

#import "DownLoadHandle.h"
#import "PreviewFileHelper.h"

@interface MaterialAcceptResultsController()

@property (nonatomic,strong) IBOutlet GETableView *tableView;
@property (nonatomic, strong) NSMutableArray *accessoryArray;

@property (nonatomic,strong) NSDictionary *invoiceData;

@property (nonatomic,strong) NSMutableArray *subMBaseData;
@property (nonatomic,strong) NSMutableArray *deductData;

@property (strong, nonatomic) NSMutableArray *resultData;
@property (nonatomic, assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功
@property (nonatomic, assign) NSInteger downFileState;//0加载中，1未找到数据，2加载失败，3加载成功

@end

@implementation MaterialAcceptResultsController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"材料验收结果"];
        
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"补充" style:UIBarButtonItemStyleDone target:self action:@selector(replenishSelector:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.accessoryArray = [NSMutableArray array];
    self.resultData = [NSMutableArray array];
    
    NSDictionary *mDictionary = self.value;
    self.invoiceData = mDictionary;
    [self setShowInfoArray:mDictionary];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    
    //获取扣重项目
    [self getNetWorkDataYCID:mDictionary];
}

- (void)setShowInfoArray:(NSDictionary*)dic
{
    NSMutableArray *subMBase = [NSMutableArray array];
    [self addContractInfoKey:@"磅单编号" toKey:@"磅单编号：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"材料名称" toKey:@"材料名称：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"供应商" toKey:@"供  应  商：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"进厂时间" toKey:@"进厂时间：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"车辆编号" toKey:@"车辆编号：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"毛重" toKey:@"材料毛重：" defaults:@"未知" format:@"%@公斤" form:dic toArray:subMBase];
    [self addContractInfoKey:@"仓位" toKey:@"材料仓位：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"称量员" toKey:@"过磅人员：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"备注" toKey:@"处理情况：" defaults:@"无" format:nil form:dic toArray:subMBase];
    self.subMBaseData = subMBase;
    
    NSMutableArray *deductData = [NSMutableArray array];
    if(self.resultData.count > 0){
        NSArray *arrayKZ = [self.resultData objectAtIndex:0];
        for(NSDictionary *mDictionary in arrayKZ){
            NSString *name = [mDictionary objectFormatStringForKey:@"扣重项目" ];
            name = [NSString stringWithFormat:@"%@：",name];
            NSString *bl = [mDictionary objectFormatStringForKey:@"扣重比例"];
            NSString *value = [mDictionary objectFormatStringForKey:@"扣重值"];
            
            if(bl.length > 0){
                [self addContractInfoKey:@"" toKey:name defaults:[NSString stringWithFormat:@"%@%%",bl] format:nil form:dic toArray:deductData];
            } else if(value.length > 0){
                [self addContractInfoKey:@"" toKey:name defaults:[NSString stringWithFormat:@"%@KG",value] format:nil form:dic toArray:deductData];
            } else{
                [self addContractInfoKey:@"" toKey:name defaults:@"不扣重" format:nil form:dic toArray:deductData];
            }
        }
    }
    self.deductData = deductData;
    
    [self.tableView reloadData];
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getPassingParameter:(id)object
{
    //提前加载预绘制项目
    NSInteger section = [self numberOfSectionsInTableView:_tableView];
    for (int i=0; i<section; i++) {
        NSInteger row = [self tableView:_tableView numberOfRowsInSection:i];
        for(int j=0; j<row; j++){
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
            [self tableView:_tableView cellForRowAtIndexPath:indexPath];
        }
    }
}

#pragma mark 网络获取数据

- (void)getNetWorkDataYCID:(NSDictionary*)mDictionary
{
    NSString *Id = [mDictionary objectFormatStringForKey:@"Id"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"YCYS_GET_INFO"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"ID" value:Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = result.resultArray;
        [self.resultData removeAllObjects];
        
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            self.orderContentState = 3;
            self.downFileState = 3;
            
            //处理无数据情况
            if(self.resultData.count >= 2){
                NSArray *arrayKZ = [self.resultData objectAtIndex:0];
                NSArray *arrayImg = [self.resultData objectAtIndex:1];
                if(arrayKZ.count<=0) self.orderContentState = 1;
                if(arrayImg.count<=0) self.downFileState = 1;
            }
            [self setShowInfoArray:mDictionary];
            
        } else {
            self.orderContentState = 1;
            self.downFileState = 1;
            [self.tableView reloadData];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        self.downFileState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        self.downFileState = 2;
        [self.tableView reloadData];
    }];
    
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 2 && self.resultData.count >= 2) {
        NSArray *array = [self.resultData objectAtIndex:1];
        return array.count > 0 ? array.count : 1;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"CreateContractViewController%ld%ld",indexPath.section,indexPath.row];
    GEInputTableViewCell *cell = [self.tableView getCellViewInRow:indexPath.row inSection:indexPath.section];
    if (cell != nil) return cell;
    
    //过磅材料明细
    if(indexPath.section == 0){
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        [cell setDataArray:self.subMBaseData];
        return cell;
    }
    
    //扣重明细
    if(indexPath.section == 1){
        if (self.orderContentState == 3) {
            AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            [cell setDataArray:self.deductData];
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
            cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 50);
            
            if(self.orderContentState == 0){//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 30.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"无扣重项目";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"数据加载失败";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    //见证取样
    else if(indexPath.section == 2){
        if (self.downFileState == 3) {
            DownFileInfoCell *cell = [[DownFileInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
            NSArray *arrayImg = [self.resultData objectAtIndex:1];
            NSDictionary *fileDictionary = [arrayImg objectAtIndex:indexPath.row];
            cell.fileName.text = [fileDictionary objectFormatStringForKey:@"图片名称"];
            cell.fileSize.text = [fileDictionary objectFormatStringForKey:@"图片大小" defaults:@"未知"];
            cell.iconImageView.image = [FileTypeIcon setFileTypeIcon:[fileDictionary objectFormatStringForKey:@"图片路径"]];
            
            cell.downButton.userInteractionEnabled = YES;
            cell.downButton.tag = indexPath.row;
            [cell.downButton addTarget:self action:@selector(downadjunctFile:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
            cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 50);
            
            if(self.downFileState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 30.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.downFileState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"无取样图片";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.downFileState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"数据加载失败";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView *viewBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    viewBackground.backgroundColor = [UIColor whiteColor];
    [view addSubview:viewBackground];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    if(section == 0){
        lable.text = @"过磅材料明细";
    } else if(section == 1){
        lable.text = @"材料扣重项目";
    } else if(section == 2){
        lable.text = @"材料取样明细";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 4) return 0.0001;
    else return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.subMBaseData];
        return cell.contentView.frame.size.height;
        
    } else if (indexPath.section == 1) {
        if(self.orderContentState == 3){
            AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
            [cell setDataArray:self.deductData];
            return cell.contentView.frame.size.height;
        }
    }
   
    return 54;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //预览文件
    if(indexPath.section == 2 && self.downFileState == 3) {
        if(self.resultData.count<2) return;
        NSArray *arrayImg = [self.resultData objectAtIndex:1];
        if(indexPath.row > arrayImg.count) return;
        
        NSDictionary *fileDictionary = [arrayImg objectAtIndex:indexPath.row];
        NSString *fileName = [fileDictionary objectFormatStringForKey:@"图片名称"];
        NSString *filePath = [fileDictionary objectFormatStringForKey:@"图片路径"];
        
        //ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
        //filePath = [NSString stringWithFormat:@"%@/upload/%@",model.IpAddress,filePath];
        
        //创建连接，预览文件
        PreviewFileHelper *preview = [[PreviewFileHelper alloc] init];
        [preview startPreviewExternalFile:filePath fileName:fileName];
    }
    
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    [super backResultDataKey:key dataValue:backValue];
    
    //清理并重新加载
    self.orderContentState = 0;
    self.downFileState = 0;
    [self.tableView reloadData];
    
    //获取扣重项目
    [self getNetWorkDataYCID:self.invoiceData];
}

#pragma mark Button Event

- (void)downadjunctFile:(UIButton*)button
{
    //下载附件
    if(self.resultData.count<2) return;
    NSArray *arrayImg = [self.resultData objectAtIndex:1];
    if(button.tag > arrayImg.count) return;
    
    NSDictionary *fileDictionary = [arrayImg objectAtIndex:button.tag];
    NSString *fileName = [fileDictionary objectFormatStringForKey:@"图片名称"];
    NSString *filePath = [fileDictionary objectFormatStringForKey:@"图片路径"];
    
    //ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
    //filePath = [NSString stringWithFormat:@"%@/upload/%@",model.IpAddress,filePath];
    
    //创建连接，下载文件
    DownLoadHandle *downLoad = [[DownLoadHandle alloc] init];
    [downLoad startDownExternalFile:filePath fileName:fileName];
}

- (void)replenishSelector:(id)selector
{
    MaterialAcceptResultsAddController *viewController = [[MaterialAcceptResultsAddController alloc] initWithValue:self.invoiceData];
    viewController.backResultDelagate = self;
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

@end

